import { reactive, ref } from 'vue'
import { type UserAddress } from '@/types/user'
import {
  createAddressApi,
  deleteAddressApi,
  getAddressApi,
  getUserAddressesApi,
  updateAddressApi,
} from '@/api/userAddress'
import { type FormInstance, type FormRules } from 'element-plus'
export default function () {
  // 用户d地址列表
  const addressList = ref<UserAddress[]>([])

  // 用户新建地址表单
  const addressForm = ref<UserAddress>({
    name: '',
    phone: '',
    address: '',
  })

  // 获取用户地址列表
  const getAddressList = async () => {
    const res = await getUserAddressesApi()
    if (res.code === 0) {
      addressList.value = res.data
    } else {
      ElMessage.warning(res.msg)
    }
  }

  // 设置默认地址
  const setDefaultAddress = async (selectedAddress: UserAddress) => {
    try {
      // 选出旧的默认地址
      const oldDefaultAddress = addressList.value.find(address => address.isDefault === '1')
      // 更新选中地址为默认地址
      selectedAddress.isDefault = '1'
      // 更新本地数据
      addressList.value.forEach(address => {
        address.isDefault = address.id === selectedAddress.id ? '1' : '0'
      })
      // 如果有旧的默认地址，更新为非默认地址
      if (oldDefaultAddress) {
        oldDefaultAddress.isDefault = '0'
        await updateAddressApi(oldDefaultAddress!)
      }
      // 发送请求更新数据库
      await updateAddressApi(selectedAddress)
    } catch (error) {
      console.error('更新默认地址失败', error)
      // 提示用户更新失败
      ElMessage.error('设置默认地址失败')
    }
  }

  // 表单校验
  const rules = reactive<FormRules<UserAddress>>({
    name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入收货人电话', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' },
    ],
    address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
  })

  // 新增地址
  const saveAddress = async (formEl: FormInstance | undefined) => {
    // 如果表单校验不通过，直接返回
    if (!formEl) return
    await formEl.validate()
    try {
      // 否则为新增地址
      const res = await createAddressApi(addressForm.value)
      if (res.code !== 0) {
        // 提示用户保存失败
        ElMessage.error(res.msg)
        return
      }
      ElMessage.success('新增地址成功')
      // 重新获取地址列表
      getAddressList()
      // 重置表单
      resetForm(formEl)
    } catch (error) {
      console.error('保存地址失败', error)
      // 提示用户保存失败
      ElMessage.error('保存地址失败')
    }
  }

  // 删除地址
  const deleteAddress = async (id:string) => {
    try {
      const res = await deleteAddressApi(id)
      if (res.code === 0) {
        ElMessage.success('删除地址成功')
        // 重新获取地址列表
        getAddressList()
      } else {
        ElMessage.error('删除地址失败')
      }
    } catch (error) {
      console.error('删除地址失败', error)
      ElMessage.error('删除地址失败')
    }
  }
  // 重置表单
  const resetForm = (formEl: FormInstance | undefined) => {
    if (formEl) {
      formEl.resetFields()
    }
  }

  // 根据地址ID查询地址
  const getAddress = async (id: string) => {
    const res = await getAddressApi(id)
    if (res.code === 0) {
      addressForm.value = res.data
    } else {
      ElMessage.warning(res.msg)
    }
  }
  // 编辑地址
  const updateAddress = async (formEl: FormInstance | undefined) => {
    // 如果表单校验不通过，直接返回
    if (!formEl) return
    await formEl.validate()
    // 否则为编辑地址
    try {
      const res = await updateAddressApi(addressForm.value)
      if (res.code !== 0) {
        // 提示用户编辑失败
        ElMessage.error(res.msg)
        return
      }
      ElMessage.success('编辑地址成功')
      // 重新获取地址列表
      getAddressList()
      // 重置表单
      resetForm(formEl)
    } catch (error) {
      console.error('编辑地址失败', error)
      // 提示用户编辑失败
      ElMessage.error('编辑地址失败')
    }
  }
  return {
    addressList,
    addressForm,
    rules,
    resetForm,
    getAddressList,
    setDefaultAddress,
    saveAddress,
    deleteAddress,
    updateAddress,
    getAddress,
  }
}
